﻿@using SmartStore.Admin.Models.DataExchange;
@model List<ExportProfileModel>
@{
    ViewBag.Title = T("Common.Export").Text;

    var hasUserProfiles = Model.Any(x => !x.IsSystemProfile);
    var hasSystemProfiles = Model.Any(x => x.IsSystemProfile);
}

<div class="section-header">
    <div class="title">
		<i class="fa fa-upload"></i>
		<span>@T("Common.Export")</span>
    </div>

	<div class="options">
		<a href="javascript:void(0)" data-url="@Url.Action("Create")" class="btn btn-primary export-profile-button">
			<i class="fa fa-plus"></i>
			<span>@T("Admin.DataExchange.AddNewProfile")</span>
		</a>
	</div>
</div>

<div id="ExportProfileListContainer">
	@{
        Html.RenderPartial("_ProfileList", Model.Where(x => !x.IsSystemProfile), new ViewDataDictionary { { "IsSystemProfile", false } });
        Html.RenderPartial("_ProfileList", Model.Where(x => x.IsSystemProfile), new ViewDataDictionary { { "IsSystemProfile", true } });
    }
</div>

@{Html.SmartStore().Window()
	.Name("export-profile-dialog")
	.Size(WindowSize.Large)
	.FooterContent(@<text>
		<button class="btn btn-secondary btn-flat" data-dismiss="modal"><span>@T("Common.Cancel")</span></button>
		<button class="btn btn-primary"><span>@T("Common.OK")</span></button>
	</text>)
	.Render();
}

@{Html.SmartStore().Window()
	.Name("export-profile-file-dialog")
	.Title(T("Admin.DataExchange.Export.ExportFiles"))
	.Size(WindowSize.FlexSmall)
	.FooterContent(@<text>
		<button class="btn btn-secondary btn-flat" data-dismiss="modal"><span>@T("Common.Cancel")</span></button>
	</text>)
	.Render();
}

<script type="text/javascript">

	jQuery(document).ready(function () {
		var dialog = $('#export-profile-dialog');

		// show profile dialog
		$(document).on('click', '.export-profile-button', function (e) {
			e.preventDefault();

			dialog.find('.modal-body').empty();
			dialog.find('.modal-title').text(dialog.attr('data-profile') + ' - ' + $.trim($(this).text()));
			showPrimaryButton(false);

			$(this).doAjax({
				type: 'GET',
				smallIcon: dialog.find('.modal-body'),
				callbackSuccess: function (resp) {
					dialog.find('.modal-body').html(resp);

					$('select[name="ProviderSystemName"]').selectWrapper({
						minimumResultsForSearch: 16,
						templateResult: providerSelectItemFormatting,
						templateSelection: providerSelectItemFormatting
					});

					toggleProviderDescription();

					$('select[name="CloneProfileId"]').selectWrapper({
						allowClear: true,
						minimumResultsForSearch: 16,
						templateResult: profileSelectItemFormatting,
						templateSelection: profileSelectItemFormatting
					});
				},
				callbackComplete: function () {
					showPrimaryButton(true);
				}
			});

			dialog.modal('show');
			return false;
		});

		// show profile file dialog
		$(document).on('click', '.export-file-count', function (e) {
			e.preventDefault();
			var fileDialog = $('#export-profile-file-dialog'),
				id = $(this).closest('tr').attr('data-profile-id');

			fileDialog.find('.modal-body').empty();

			$({}).doAjax({
				type: 'GET',
				url: '@Url.Action("ProfileFileDetails")?deploymentId=0&profileId=' + id,
				smallIcon: fileDialog.find('.modal-body'),
				callbackSuccess: function (response) {
					fileDialog.find('.modal-body').html(response);
				}
			});

			fileDialog.modal('show');
			return false;
		});

		// submit dialog form
		dialog.on('click', '.btn-primary', function () {
			var form = dialog.find('.export-profile-form');

			if (!form.length) {
				dialog.modal('hide');
				return;
			}

			form.submit();
		});

		// selected provider changed
		$(document).on('change', 'select[name="ProviderSystemName"]', toggleProviderDescription);


		function showPrimaryButton(display) {
			var button = $('#export-profile-dialog').find('.btn-primary').toggle(display);
		}

		function toggleProviderDescription() {
			dialog.find('.export-provider-description').hide();

			var option = dialog.find('select[name="ProviderSystemName"]').find(':selected');
			$('#ExportProviderDescription' + option.attr('data-id')).fadeIn('fast');
		}

		function providerSelectItemFormatting(item) {
			try {
				var option = $(item.element);

				// item.element is undefined for selection formatting
				if (option.length === 0) {
					option = $('select[name="ProviderSystemName"]').find('option[value="' + item.id + '"]');
				}

				var html = '<div class="form-row flex-nowrap align-items-center">',
					imageUrl = option.data('imageurl');

				if (imageUrl)
					html += '<div class="col" style="max-width:48px; width:48px"><div class="img-center-container"><img class="img-fluid" src="' + imageUrl + '" /></div></div>';

				html += '<div class="col">';
				html += '<div class="fs-xs font-weight-medium" style="line-height:1.2">' + item.text + '</div>';
				html += '<div class="text-muted fs-xs">' + option.attr('value') + '</div>';
				html += '</div>';
				html += '</div>';

				return $(html);
			}
			catch (e) { }

			return item.text;
		}

		function profileSelectItemFormatting(item) {
			try {
				var option = $(item.element);

				// item.element is undefined for selection formatting
				if (option.length === 0) {
					option = $('select[name="CloneProfileId"]').find('option[value="' + item.id + '"]');
				}

				var html = '<div class="form-row flex-nowrap align-items-center h-100">',
					imageUrl = option.data('imageurl');

				if (imageUrl)
					html += '<div class="col" style="max-width:48px; width:48px"><div class="img-center-container"><img class="img-fluid" src="' + imageUrl + '" /></div></div>';

				html += '<div class="col">';
				html += '<div class="fs-xs font-weight-medium" style="line-height:1.2">' + item.text + '</div>';
				if (option.attr('data-systemname')) {
					html += '<div class="text-muted fs-xs">' + option.attr('data-systemname') + '</div>';
				}
				
				html += '</div>';
				html += '</div>';

				return $(html);
			}
			catch (e) { }

			return item.text;
		}


		// start export task
		$(document).on('click', '.btn-run-task', function (e) {
			e.preventDefault();
			$(this).doPostData({
				ask: @T("Admin.Common.AskToProceed").JsText
			});
			return false;
		});

		SmartStore.Admin.TaskWatcher.startWatching({
			context: $('#ExportProfileListContainer'),
			elementsSelector: '.task-progress',
			defaultProgressMessage: @T("Admin.System.ScheduleTasks.RunNow.IsRunning").JsText,
			pollUrl: '@Url.Action("GetRunningTasks", "ScheduleTask")',
			onTaskStarted: function (task, el) {
				var tr = el.closest('tr');

				tr.find('.btn-run-task').addClass('hide');
				tr.find('.btn-cancel-task').removeClass('hide');
				tr.find('.btn-log').addClass('hide');
				tr.find('.next-run-info').addClass('hide');
				
				$('body, html').animate({ scrollTop: tr.offset().top - 70 }, 'slow');
			},
			onTaskCompleted: function (taskId, el) {
				var tr = el.closest('tr'),
					profileId = tr.attr('data-profile-id');

				tr.find('.btn-run-task').removeClass('hide');
				tr.find('.btn-cancel-task').addClass('hide');
				tr.find('.btn-log').removeClass('hide');

				$.ajax({
					cache: false,
					global: false,
					type: 'POST',
					url: '@Url.Action("GetTaskRunInfo", "ScheduleTask")',
					data: { id: taskId },
					success: function (data) {
						tr.find('.next-run-info').html(data.nextRunHtml).removeClass('hide');
						tr.find('.last-run-info').html(data.lastRunHtml);
					}
				});

				$.get('@Url.Action("ProfileListDetails")?profileId=' + profileId, function (response) {
					$('#ExportFileCount' + profileId).html(response || '');
				});
			}
		});
	});
</script>